<template>
  <div class="nav-box">
    <nav id="main-navbody" class="main-nav container">
      <ul
        class="main"
        :class="{ 'hide-submenu': toggleHide }"
        :style="{ 'padding-right': row > 1 ? '40px' : '0' }"
      >
        <template v-for="(om, idxom) in cpMenusData">
          <li
            v-show="col * nowRow - 1 < idxom && idxom < col * (nowRow + 1)"
            v-if="om.subMenu.length > 0"
            :key="idxom"
            class="menu-cell"
            @mouseover="menuAlign"
          >
            <div
              class="tap"
              :class="{ tapnomore: !om.subMenu }"
              :url="om.sysUrl"
              :query="om.query"
              :title="om.label"
              @click="toPage(om.sysUrl, om.label, om.code)"
            >
              <span>{{ om.label }}</span>
            </div>
            <main-nav-item
              v-if="om.subMenu"
              :data="om.subMenu"
              :menus-data="menusData"
              :flat-menus="flatMenus"
              :right="col * (nowRow + 1) - idxom < 7 ? true : false"
              :class-name="`extra-menu ${
                col * (nowRow + 1) - idxom < 7 ? 'right-menu' : 'left-menu'
              }`"
            />
          </li>
        </template>
      </ul>
      <div v-if="row > 1" class="operation-wrap">
        <i class="icon el-icon-setting" @click="showEditMenu" />
        <div class="main-nav-arrow">
          <i
            class="el-icon-caret-top"
            :class="nowRow > 0 ? 'active' : ''"
            @click="prevRow"
          />
          <i
            class="el-icon-caret-bottom"
            :class="nowRow < row - 1 ? 'active' : ''"
            @click="nextRow"
          />
        </div>
      </div>
      <div v-else class="operation-wrap">
        <i class="icon el-icon-setting" @click="showEditMenu" />
      </div>
    </nav>
    <div v-show="!homeHide" class="indicantor fwidth">
      <a v-for="(item, index) in guideData" :key="index" :href="item.url">
        {{ item.label }}
      </a>
    </div>
  </div>
</template>
<script>
import { TypeOf } from 'src/utils/funcs';
import MainNavItem from './main-item.vue';
import toPage from 'src/mixins/toPage';

const MAIN_MENUS = require('constant').CONFIG.MAIN_MENUS;

export default {
  name: 'MainNav',
  components: {
    MainNavItem
  },
  mixins: [toPage],
  props: {
    flatMenus: {
      type: Array,
      default: () => {
        return [];
      }
    },
    dialogVisible: {
      type: Boolean,
      default: true
    },
    homeHide: {
      type: Boolean,
      default: true
    },
    menusData: {
      type: Array,
      required: false,
      default: function() {
        return [];
      }
    },
    appPath: {
      // 应用路径，默认根目录
      type: String,
      default: '/'
    }
  },
  data() {
    return {
      iframe: null,
      nowRow: 0,
      row: 0, // 菜单行数
      col: 0, // 菜单列数
      toggleHide: false, // 默认隐藏子菜单
      guideData: [], // 指示数据
      homeShow: true,
      hashMenus: location.hash.replace('#/', '').split('/')
    };
  },
  computed: {
    // 过滤 subMenu
    cpMenusData() {
      const data = this.menusData || MAIN_MENUS;

      for (const cell of data) {
        for (const sub of cell['subMenu']) {
          if (!sub['label'] || !/[\W\w]+/i.test(sub['label'])) {
            sub['label'] = false;
          }
        }
        if (cell['subMenu'] && cell['subMenu'].length < 1) {
          cell['subMenu'] = false;
        }
      }
      this.computerMenuRows();
      return data;
    },
    pathname() {
      return location.pathname.replace(/^\//, '');
    }
  },

  watch: {
    hashMenus(n, o) {
      if (n !== o) {
        this.initIndicant();
      }
    }
  },
  mounted() {
    this.initIndicant();
    window.addEventListener('resize', this.handleResize);
    window.toPage = this.toPage;
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    showEditMenu() {
      this.$emit('update:dialogVisible', true);
    },
    handleResize(e) {
      // console.log('测试')
      this.computerMenuRows();
    },
    // 展示上一行菜单
    prevRow() {
      if (this.nowRow > 0) {
        this.nowRow--;
      }
    },
    // 展示下一行菜单
    nextRow() {
      if (this.nowRow < this.row - 1) {
        this.nowRow++;
      }
    },
    /**
     *	计算菜单的列数和菜单行数
     */
    computerMenuRows() {
      const winWidth = window.innerWidth;
      const parentWidth = winWidth * 0.98;
      const realMenu = this.menusData.filter(
        (item) => item.subMenu && item.subMenu.length > 0
      );
      const menuLength = realMenu.length;

      const row =
        Math.floor((menuLength * 96) / parentWidth) +
        ((menuLength * 96) % parentWidth > 0 ? 1 : 0); // 行数
      const col = Math.floor((parentWidth - 40) / 96); // 列数, 40是编辑菜单按钮宽度

      this.row = row;
      this.col = col;
    },

    // 菜单定位
    menuAlign(e) {
      // console.log('展示底层页面', e);
      var bodyEl = document.querySelector('body');
      var eOffsetLeft = e.currentTarget.offsetLeft;
      var menuCell = e.currentTarget;

      if (bodyEl.clientWidth * 0.6 < eOffsetLeft) {
        var clss = menuCell.className.split(' ');
        if (clss) {
          if (clss.indexOf('toleft') < 0) { menuCell.className = `${menuCell.className} toleft`; }
        } else {
          menuCell.className = ' toleft';
        }
      }
    },
    // 路由处理
    routeGo(e) {
      const regx = /(\w+\-?\w+)+\.html/i;
      const attrs = e.target.attributes;
      const Url = attrs['url'];
      let apath = '';
      const $this = this;
      const query =
        typeof attrs['query'] !== 'undefined' ? attrs['query'].value : '';
      if (Url) {
        const cpath = location.pathname.match(regx)
          ? location.pathname.match(regx)[0]
          : '';
        const path = Url.value.match(regx) ? Url.value.match(regx)[0] : '';
        const value = Url.value.replace(regx, '');
        const act = /^[~@]{1,2}\//g.test(Url.value)
          ? Url.value.substr(0, Url.value.indexOf('/'))
          : undefined;

        if (/^(^https?:)?\/\/\w+/gi.test(Url.value)) {
          window.open(Url.value, '_blank'); // 打开其他网站页面
        } else if (act && act.indexOf('@') > -1) {
          // 打开新窗口
          window.open(
            `//${
              location.host +
              this.appPath +
              Url.value.replace(/^[~@]{1,2}\//g, '')
            }`,
            '_blank'
          );
        } else if (act && act.indexOf('~') > -1) {
          /** 支持 ~/ 跳转到根目录导航 */
          location.href = `//${
            location.host +
            this.appPath +
            Url.value.replace(/^[~@]{1,2}\//g, '')
          }`;
        } else if (this.$router && cpath === path) {
          const param = { path: value === '' ? '/' : value };
          if (typeof query === 'string' && query !== '') { param['query'] = JSON.parse(query); }
          this.$router.push(param);
        } else {
          apath =
            location.pathname.replace(regx, '') === '/'
              ? this.appPath
              : location.pathname.replace(regx, '');
          location.href = `//${location.host + apath}${path}#${value}`;
        }

        this.toggleHide = true;
        setTimeout(function() {
          $this.toggleHide = false;
        }, 1000);
      }
      this.hashMenus = location.hash.replace('#/', '').split('/');
    },
    // 获取指示器数据
    indicantPath(path, subMenus) {
      const regxhtm = /(\w+\-?\w+)+\.html/i;
      const guideData = this.guideData;
      const regx = /\/$/;
      const this$1 = this;
      let isFind = false;

      path = path.replace(regx, '');

      if (TypeOf(subMenus) === 'Array') {
        subMenus.forEach(function(item) {
          if (
            item.url &&
            item.url.indexOf(path) !== -1 &&
            item.url.replace(regx, '').length === path.replace(regx, '').length
          ) {
            guideData.push({
              label: item.label,
              url: guideData[0]['url'] + '#' + item.url.replace(regxhtm, '')
            });
            isFind = true;
          }
          if (!isFind && TypeOf(item.subMenu) === 'Array') {
            this$1.indicantPath(path, item.subMenu);
          }
        });
      }
    },
    // 初始化指示器
    initIndicant() {
      let i;
      let path;
      let submeuns;
      const this$1 = this;
      let homeUrl = 'index.html';
      const pathname = this.pathname;
      const hashMenus = this.hashMenus;
      const home = MAIN_MENUS[0]
        ? { label: MAIN_MENUS[0]['label'], url: MAIN_MENUS[0]['url'] }
        : { label: '首页', url: 'index.html' };
      this$1.guideData = [];
      this$1.guideData.push(home);
      // 获取当前单页面首地址
      MAIN_MENUS.forEach(function(item) {
        if (item.url && item.url.indexOf(pathname) !== -1) {
          homeUrl = this$1.guideData[0]['url'] = item.url;
          this$1.guideData[0]['label'] = item.label;
          submeuns = item.subMenu;
        }
      });

      for (i = 0; i < hashMenus.length; i++) {
        if (path) {
          path += '/' + hashMenus[i];
        } else {
          path = homeUrl + '/' + hashMenus[i];
        }
        this.indicantPath(path, submeuns);
      }

      this.$nextTick(function() {
        if (this.guideData.length < 2 && this.homeHide) {
          this.homeShow = false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.menu-cell {
  position: relative;
  z-index: 1000;
  &:hover {
    & > div {
      display: block;
    }
  }
}
.main-nav {
  position: relative;
  z-index: 1000;
  .main {
    padding-right: 40px;
    height: 36px;
    width: 100%;
    transition: all 0.3s;
  }
}
.operation-wrap {
  display: flex;
  position: absolute;
  top: 4px;
  right: 1%;
  height: 36px;
  line-height: 36px;
  i {
    display: block;
    color: #4d8dde;
    cursor: pointer;
  }
  i.active,
  i.icon {
    color: #fff;
  }
  .icon {
    padding-top: 4px;
    padding-right: 6px;
    font-size: 18px;
  }
}
</style>
